package com.example.demo.controller;


import ch.qos.logback.core.subst.Token;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.utils.DateUtil;
import com.example.demo.vo.UserVo;
import com.example.demo.service.UserService;
import com.example.demo.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 用户控制器
 *
 * @author He Dong
 * @date 2023/12/12
 */
@RestController
@Slf4j
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     *
     * @param login 登录
     * @return {@code Result}
     */
    @PostMapping("/login")
    public Result login(@RequestBody User login) {
        if (!login.getAccount().isEmpty() && !login.getPassword().isEmpty()) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("account", login.getAccount());
            User user = userService.getOne(wrapper);
            if (user != null) {
                if (user.getPassword().equals(login.getPassword())) {
                    // 生成一个 JWT
                    String token = TokenUtils.genToken(user.getAccount(), user.getPassword());
                    redisTemplate.opsForValue().set("token:" + user.getAccount(), token, 2, TimeUnit.HOURS);
                    Map<String, String> map=new HashMap<>();
                    map.put("token",token);
                    map.put("id", String.valueOf(user.getId()));
                    map.put("name", user.getName());
                    map.put("account", user.getAccount());
                    map.put("roleId",String.valueOf(user.getRoleId()));
                    map.put("phone",user.getPhone());
                    map.put("mailbox",user.getMailbox());
                    map.put("wechat",user.getWechat());
                    map.put("qq",user.getQq());
                    map.put("loginTime",DateUtil.getDate());
                    map.put("logoutTime",user.getLogoutTime());
                    map.put("createTime",user.getCreateTime());
                    user.setLoginTime(DateUtil.getDate());
                    userService.update(user,wrapper);
                    log.info("登录成功");
                    return Result.success("登录成功", map);
                }
            } else {
                log.info("用户不存在");
                return Result.error("用户不存在");
            }
        }
        log.info("账号密码不能为空");
        return Result.error("账号密码不能为空");
    }

    /**
     * 注销
     *
     * @return {@code Result}
     */
    @GetMapping("/logout")
    public Result logout() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String account = JWT.decode(token).getAudience().get(0);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("account",account);
        User user = userService.getOne(wrapper);
        user.setLogoutTime(DateUtil.getDate());
        UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
        userUpdateWrapper.eq("account",account);
        userService.update(user,wrapper);
        redisTemplate.delete("token:" + account);
        return Result.success("注销成功");
    }


    /**
     * 修改密码
     *
     * @param changePassword 新密码
     * @param password       密码
     * @param account        账号
     * @return {@code User}
     */
    @PostMapping("/changePassword")
    public String changePassword(@RequestParam String changePassword, @RequestParam String password, @RequestParam String account) {
        String hashedPassword = BCrypt.hashpw(changePassword, BCrypt.gensalt());
        QueryWrapper<User> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq("account", account);
        User user = userService.getOne(wrapperUser);
        if (!BCrypt.checkpw(password, user.getPassword())) {
            return "原密码不正确！";
        }
        if (BCrypt.checkpw(changePassword, user.getPassword())) {
            return "新密码与原来的密码重复！";
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("account", account); // 设置更新条件为id字段等于传入的id参数
        User updatedUser = new User();
        updatedUser.setPassword(hashedPassword); // 设置要更新的密码字段
        boolean updateResult = userService.update(updatedUser, wrapper);
        if (updateResult) {
            // 更新成功
            return "200";
        } else {
            // 更新失败
            return "401";
        }
    }

}

